from symbide import ModuleManager
from symbide.src.parsing import parsers 

from symbide.src.utils import createUniquePath 
from parser import Parser

import os
from shutil import copyfile

if ModuleManager.hasModule('gtk'):
    import gtk

from xml.dom import minidom

class Exporter(Parser):
    '''
    Exports Symbide worksheets as html/css or xml/xsl files. Also copies all plots
    and images to a subfolder and adds <img src=".."> tags.
    '''
        
    def export(self, DOM, stylePath, path=None):
        styleName = os.path.basename(stylePath)
        if path:
            styleDir, plotDir = self._makeDirs(path)
            self._copyPlots(DOM, plotDir)
            copyfile(str(stylePath), str(os.path.join(styleDir,styleName)))
        
        mode = os.path.splitext(stylePath)[1]
        if mode=='.xsl':
            xmlDef = '<?xml version="1.0" encoding="utf-8"?>\n'
            styleDef = '<?xml-stylesheet href="stylesheets/%s" type="text/xml"?>\n'%styleName
            data = xmlDef+styleDef+DOM.toxml()
        elif mode=='.css':
            data = parsers['html'].transform(DOM, "stylesheets/%s"%styleName)
        else:
            return None
        
        if not path:
            return data
        
        f = open(path, 'w')
        f.write(data)
        f.close() 
    
    def _makeDirs(self, path):
        styleDir = os.path.join(os.path.dirname(path),'stylesheets')
        if not os.path.exists(styleDir):
            os.mkdir(styleDir)
        
        plotDir = os.path.join(os.path.dirname(path),'plots')
        if not os.path.exists(plotDir):
            os.mkdir(plotDir)
        
        return styleDir, plotDir

    
    def _copyPlots(self, DOM, plotDir):
        #copy all images into the plot-folder and redirect the img-paths
        for n in DOM.getElementsByTagName('img'):
            oldPath = n.getAttribute('src')
            oldName = os.path.basename(oldPath)
            ext = os.path.splitext(oldName)[1]
            newPath, name = createUniquePath(plotDir, 'plot', '.png', return_name=True)
            if ext!='.png':
                if not ModuleManager.hasModule('gtk'):
                    #TODO: handle this error over logger
                    raise 
                im = gtk.Image()
                im.set_from_file(oldPath)
                pixbuf = im.get_pixbuf()
                pixbuf.save(newPath, 'png')
            else:
                copyfile(str(oldPath), str(newPath))
            n.setAttribute('src', 'plots/%s'%name)
        
        #replace all plot tags with <img src> tags
        for n in DOM.getElementsByTagName('symbide_plot')+DOM.getElementsByTagName('latex'):
            oldPath = n.getAttribute('path')
            oldName = os.path.basename(oldPath)
            ext = os.path.splitext(oldName)[1]
            newPath, name = createUniquePath(plotDir, 'plot', ext, return_name=True)
            copyfile(str(oldPath), str(newPath))
            img = minidom.Element('img')
            img.setAttribute('src', 'plots/%s'%name)
            n.parentNode.replaceChild(img, n)
        """    
        #replace all math tags with <img src> tags
        for n in DOM.getElementsByTagName('latex'):
            oldPath = n.getAttribute('path')
            oldName = os.path.basename(oldPath)
            ext = os.path.splitext(oldName)[1]
            newPath, name = createUniquePath(plotDir, 'plot', ext, return_name=True)
            copyfile(str(oldPath), str(newPath))
            img = minidom.Element('img')
            img.setAttribute('src', 'plots/%s'%name)
            n.parentNode.replaceChild(img, n)
           """  